import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    
    // 验证项目是否存在
    const project = await db.researchProject.findUnique({
      where: { id }
    })
    
    if (!project) {
      return NextResponse.json(
        { error: 'Research project not found' },
        { status: 404 }
      )
    }

    // 获取项目的历史记录
    const histories = await db.projectHistory.findMany({
      where: { projectId: id },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            email: true
          }
        }
      },
      orderBy: {
        createdAt: 'desc'
      }
    })

    return NextResponse.json(histories)
  } catch (error) {
    console.error('Error fetching project histories:', error)
    return NextResponse.json(
      { error: 'Failed to fetch project histories' },
      { status: 500 }
    )
  }
}

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    const body = await request.json()
    
    // 验证项目是否存在
    const project = await db.researchProject.findUnique({
      where: { id }
    })
    
    if (!project) {
      return NextResponse.json(
        { error: 'Research project not found' },
        { status: 404 }
      )
    }

    const {
      action,
      description,
      userId,
      fromLevel1,
      fromLevel2,
      fromLevel3,
      fromLevel4,
      toLevel1,
      toLevel2,
      toLevel3,
      toLevel4
    } = body

    // 验证必填字段
    if (!action || !userId) {
      return NextResponse.json(
        { error: 'Missing required fields: action, userId' },
        { status: 400 }
      )
    }

    // 创建历史记录
    const history = await db.projectHistory.create({
      data: {
        projectId: id,
        action,
        description: description || '',
        userId,
        fromLevel1,
        fromLevel2,
        fromLevel3,
        fromLevel4,
        toLevel1,
        toLevel2,
        toLevel3,
        toLevel4
      },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            email: true
          }
        }
      }
    })

    return NextResponse.json(history)
  } catch (error) {
    console.error('Error creating project history:', error)
    return NextResponse.json(
      { error: 'Failed to create project history' },
      { status: 500 }
    )
  }
}